<!--业务实体选择对话框组件-->
<!--created by yuyupeng 2023/12/05-->
<template>
  <div>
    <!--按钮-->
    <a-button @click="openModal">
      <template #icon>
        <icon-storage />
      </template>
      {{ buttonWord }}
    </a-button>

    <!--抽屉：选择表-->
    <a-modal
      :visible="visible"
      :width="width"
      :title="title"
      :mask-closable="maskClosable"
      :ok-loading="okLoading"
      @cancel="closeDrawer"
      @ok="selectBusinessEntity"
    >
      <!--查询-->
      <TableSearch
        ref="searchRef"
        expand
        :data-source="SEARCH_FORM"
        @change="searchByParams"
      />

      <!--表格-->
      <a-table
        v-model:selected-keys="selectedKeys"
        :columns="COLUMNS_TABLE"
        :data="tbData"
        row-key="id"
        :row-selection="rowSelection"
        :loading="tbLoading"
        :pagination="pagination"
        :scroll="{ x: '100%', y: 500 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        @row-click="rowClick"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, reactive, toRefs } from 'vue';
  import TableSearch from '@/common/components/cac-components/advanced-search/index.vue';
  import {
    Notification,
    TableColumnData,
    TableRowSelection,
  } from '@arco-design/web-vue';
  import { Pagination } from '@/types/global';
  import { queryBusinessEntityRecordList } from '@/api/infrastructure/business-entity';
  import {
    BusinessEntityParams,
    BusinessEntityRecord,
  } from '@/api/infrastructure/model/businessEntityModal';

  const props = defineProps({
    width: { type: String, default: '960px' }, // 对话框宽度
    title: { type: String, default: '业务实体选择' }, // 对话标题
    buttonWord: { type: String, default: '业务实体选择' }, // 按钮文字
    // onlyChosenOneEmployee: { type: Boolean, default: false }, // 是否只选择一个人员，如果true，则出现单选框，如果false，则出现复选框
    maskClosable: { type: Boolean, default: true }, // 控制是否允许点击蒙层关闭弹窗
    // cancelText: { type: String, default: '取消' }, // 按钮文字
    // submitWithClose: { type: Boolean, default: true }, // 用于控制submit回调时，是否进行close操作
    // unmountOnClose: { type: Boolean, default: true }, // 关闭时销毁 Modal 里的子元素
    // okButtonProps: { type: Object, default: () => {} },
    // cancelButtonProps: { type: Object, default: () => {} },
    defaultCheckedBusinessEntityIdList: { type: Array, default: () => [] }, // 默认选中的业务实体列表，例如['id']
  });

  const {
    width, // 对话框宽度
    title, // 对话标题
    buttonWord, // 按钮文字
    maskClosable, // 控制是否允许点击蒙层关闭弹窗
    // cancelText, // 按钮文字
    // submitWithClose, // 用于控制submit回调时，是否进行close操作
    // unmountOnClose, // 关闭时销毁 Modal 里的子元素
    // okButtonProps,
    // cancelButtonProps,
    defaultCheckedBusinessEntityIdList, // 默认选中的业务实体列表，例如['id']
  } = toRefs(props); // 根据props创建多个 ref 对象

  const emits = defineEmits(['afterSubmit']);
  const visible = ref<boolean>(false);
  const okLoading = ref<boolean>(false);

  const tbData = ref<BusinessEntityRecord[]>([]);
  const tbLoading = ref<boolean>(false);
  const searchRef = ref<any>();
  const SEARCH_FORM = computed(() => {
    return [
      /* { type: 'text', labelText: '', fieldName: 'id'}, */
      { type: 'text', labelText: '实体名称', fieldName: 'alias' },
      { type: 'text', labelText: '实体编码', fieldName: 'name' },
      /* { type: 'text', labelText: '数据源', fieldName: 'datasource'},
      { type: 'text', labelText: '自定义sql', fieldName: 'sql'},
      { type: 'text', labelText: '创建者', fieldName: 'creator'},
      { type: 'text', labelText: '创建时间', fieldName: 'createTime'},
      { type: 'text', labelText: '更新者', fieldName: 'updater'},
      { type: 'text', labelText: '更新时间', fieldName: 'updateTime'},
      { type: 'text', labelText: '是否删除', fieldName: 'deleted'}, */
    ];
  });

  const rowSelection = reactive<TableRowSelection>({
    type: 'radio',
  });
  const selectedKeys = ref<string[]>([]);
  // 分页，默认第1页，每页10条
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    showPageSize: true,
    showTotal: true,
  };
  const pagination = reactive({
    ...basePagination,
  });
  const searchParams = ref<BusinessEntityRecord>();

  const COLUMNS_TABLE: TableColumnData[] = [
    {
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      fixed: 'left',
      width: 60,
      render: (row: any) => row.rowIndex + 1,
    },
    /* { title: '', dataIndex: 'id', fixed: 'left', ellipsis: true, align: 'center', tooltip: true },
    { title: '查看', fixed: 'left', align: 'center', width: 100, slotName: 'detail' }, */
    {
      title: '实体名称',
      dataIndex: 'alias',
      width: 150,
      align: 'center',
      tooltip: true,
    },
    {
      title: '实体编码',
      dataIndex: 'name',
      width: 150,
      ellipsis: true,
      align: 'center',
      tooltip: true,
    },
    // { title: '数据源', dataIndex: 'datasource', width: 150, ellipsis: true, align: 'center', tooltip: true },
    /* {
      title: '自定义sql',
      dataIndex: 'sql',
      width: 250,
      ellipsis: true,
      align: 'center',
    }, */
    {
      title: '创建者',
      dataIndex: 'creator',
      width: 150,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
      ellipsis: true,
      align: 'center',
    },
    // { title: '更新者', dataIndex: 'updater', width: 150, ellipsis: true, align: 'center', tooltip: true },
    // { title: '更新时间', dataIndex: 'updateTime', width: 150, ellipsis: true, align: 'center', tooltip: true },
    // { title: '是否删除', dataIndex: 'deleted', width: 150, ellipsis: true, align: 'center', tooltip: true },
  ];

  const openModal = () => {
    searchRef.value.handleSubmit();
    selectedKeys.value = defaultCheckedBusinessEntityIdList.value as string[];
    visible.value = true;
  };
  const closeDrawer = () => {
    selectedKeys.value = [];
    visible.value = false;
    searchRef.value.resetSearchForm();
  };
  const selectBusinessEntity = () => {
    try {
      okLoading.value = true;
      emits(
        'afterSubmit',
        tbData.value.filter((item) => item.id === selectedKeys.value[0])
      );
      okLoading.value = false;
      closeDrawer();
    } catch (error) {
      okLoading.value = false;
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    }
  };
  /**
   * @method
   * @description 按条件搜索
   */
  const searchByParams = (reqdata: any = {}) => {
    searchParams.value = reqdata;
    getTbDataByPage();
  };
  /**
   * @method
   * @description 获取表格数据
   */
  const getTbDataByPage = async () => {
    const params: BusinessEntityParams = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...searchParams.value,
    };
    tbLoading.value = true;
    selectedKeys.value = [];
    try {
      console.log(params);
      const { data } = await queryBusinessEntityRecordList(params);
      tbData.value = data.list;
      pagination.total = Number(data.total); // 用Number函数转一下，否则f12控制台会有警告，很不好看
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      Notification.error({
        content: `出现异常！${error}`,
        closable: true,
      });
    } finally {
      tbLoading.value = false;
    }
  };
  /**
   * @method
   * @description 页码发生变化触发
   */
  const onPageChange = (current: number) => {
    pagination.current = current;
    searchRef.value.handleSubmit();
  };
  /**
   * @method
   * @description 数据条数发生变化触发
   */
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    searchRef.value.handleSubmit();
  };
  /**
   * @description 点击表格数据行触发
   * @param record
   */
  const rowClick = (record: any) => {
    selectedKeys.value = [record.id];
  };
</script>
